package dbx

import (
	"context"
	"strings"

	"gitee.com/chunanyong/zorm"
	"gitee.com/workits/pkgs/logx"
)

const defaultDs = "default"

var dbDaos map[string]*zorm.DBDao = make(map[string]*zorm.DBDao)

func InitConn(cfgs ...Config) (err error) {
	for idx, cfg := range cfgs {
		if idx == 0 {
			cfg.Alias = defaultDs
		} else {
			if cfg.Alias == defaultDs {
				panic("`default` is a key word")
			}
		}
		if len(cfg.Alias) == 0 {
			panic("alias is empty")
		}

		dbDaos[cfg.Alias], err = zorm.NewDBDao(&zorm.DataSourceConfig{
			DSN:                   cfg.DSN,
			DriverName:            cfg.Driver,
			Dialect:               cfg.Dialect,
			SlowSQLMillis:         cfg.SlowSQLMillis,
			MaxOpenConns:          cfg.MaxOpenConns,
			MaxIdleConns:          cfg.MaxIdleConns,
			ConnMaxLifetimeSecond: cfg.ConnMaxLifetimeSecond,
			DefaultTxOptions:      nil,
		})
	}

	// 自定义SQL打印
	zorm.FuncPrintSQL = func(ctx context.Context, sqlstr string, args []any, execSQLMillis int64) {
		sqlstr = strings.Trim(sqlstr, " ")
		opt := strings.ToLower(sqlstr[:strings.Index(sqlstr, " ")])
		logx.Infof(opt, logx.String("type", "sql"), logx.String("sql", sqlstr), logx.Any("params", args), logx.Int64("timing", execSQLMillis), ctx)
	}
	// 禁止zorm输出错误日志干扰采集
	zorm.FuncLogError = func(ctx context.Context, err error) {}
	zorm.FuncLogPanic = func(ctx context.Context, err error) {}

	return
}

func GetDao(alias string) *zorm.DBDao {
	return dbDaos[alias]
}

func GetDefaultDao() *zorm.DBDao {
	return GetDao(defaultDs)
}
